<script lang="ts">
	import { RAG_PROVIDER_TYPE, type RagConfig } from '$lib/api/proto/roadmap_rag_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';

	interface Props {
		config?: RagConfig;
		roadmapId: string;
		onCancel: () => void;
		onOk: () => void;
	}
	let props: Props = $props();

	let name = $state(props.config?.basicConfig?.name ?? '');

	let providerType = $state(
		props.config?.basicConfig?.providerType ?? RAG_PROVIDER_TYPE.RAG_PROVIDER_YD_QANYTHING
	);
	let baseApiAddr = $state(
		props.config?.basicConfig?.baseApiAddr == undefined
			? getDefaultBaseApiAddr(
					props.config?.basicConfig?.providerType ?? RAG_PROVIDER_TYPE.RAG_PROVIDER_YD_QANYTHING
				)
			: props.config.basicConfig.baseApiAddr
	);
	let apiKey = $state(props.config?.basicConfig?.apiKey ?? '');

	let agentId = $state(props.config?.basicConfig?.agentId ?? ''); //只对有道QAnything有效

	function getDefaultBaseApiAddr(t: RAG_PROVIDER_TYPE) {
		if (t == RAG_PROVIDER_TYPE.RAG_PROVIDER_YD_QANYTHING) {
			return 'https://openapi.youdao.com/q_anything/api';
		} else if (t == RAG_PROVIDER_TYPE.RAG_PROVIDER_FASTGPT) {
			return 'https://cloud.fastgpt.cn/api';
		}
		return 'http://';
	}

	function valid(): boolean {
		if (providerType == RAG_PROVIDER_TYPE.RAG_PROVIDER_YD_QANYTHING && agentId.trim() == '') {
			return false;
		}
		if (name.trim() == '') {
			return false;
		}
		if (!(baseApiAddr.startsWith('http://') || baseApiAddr.startsWith('https://'))) {
			return false;
		}
		if (apiKey.trim() == '') {
			return false;
		}
		return true;
	}

	async function addConfig() {
		if (userStore.userSession == null) {
			return;
		}
		await callApi(
			appStore.roadmapRagApiClient.addConfig({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				basicConfig: {
					name: name,
					providerType: providerType,
					baseApiAddr: baseApiAddr,
					apiKey: apiKey,
					agentId: agentId
				}
			}).response
		);
		props.onOk();
		appStore.addToastMessage({
			level: 'success',
			content: '增加知识库配置成功',
			keepTime: 2000
		});
	}

	async function updateConfig() {
		if (userStore.userSession == null || props.config == undefined) {
			return;
		}
		await callApi(
			appStore.roadmapRagApiClient.updateConfig({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				ragConfigId: props.config.ragConfigId,
				basicConfig: {
					name: name,
					providerType: providerType,
					baseApiAddr: baseApiAddr,
					apiKey: apiKey,
					agentId: agentId
				}
			}).response
		);
		props.onOk();
		appStore.addToastMessage({
			level: 'success',
			content: '修改知识库配置成功',
			keepTime: 2000
		});
	}
</script>

<dialog class="modal modal-open">
	<div class="modal-box flex-col space-y-4">
		<button
			class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
			onclick={() => props.onCancel()}>✕</button
		>
		<h3 class="text-lg font-bold">
			{props.config == undefined ? '增加知识库配置' : '修改知识库配置'}
		</h3>
		<fieldset class="fieldset">
			<legend class="fieldset-legend">配置名称</legend>
			<input type="text" class="input w-full" bind:value={name} />
			<legend class="fieldset-legend">知识库类型</legend>
			<select
				class="select w-full"
				value={providerType}
				disabled={props.config != undefined}
				onclick={(e) => {
					const newType = parseInt(e.currentTarget.value) as RAG_PROVIDER_TYPE;
					providerType = newType;
					baseApiAddr = getDefaultBaseApiAddr(newType);
					apiKey = '';
				}}
			>
				<option value={RAG_PROVIDER_TYPE.RAG_PROVIDER_YD_QANYTHING}>有道QAnything</option>
				<option value={RAG_PROVIDER_TYPE.RAG_PROVIDER_FASTGPT}>FastGpt</option>
			</select>
			<div class="flex justify-end">
				{#if providerType == RAG_PROVIDER_TYPE.RAG_PROVIDER_YD_QANYTHING}
					<a target="_blank" href="https://ai.youdao.com/qanything/docs/api/chat">查看相关文档</a>
				{:else if providerType == RAG_PROVIDER_TYPE.RAG_PROVIDER_FASTGPT}
					<a target="_blank" href="https://doc.fastgpt.io/docs/development/openapi/intro/"
						>查看相关文档</a
					>
				{/if}
			</div>
			<legend class="fieldset-legend">API地址 </legend>
			<input
				type="text"
				class="input w-full {baseApiAddr.startsWith('http://') || baseApiAddr.startsWith('https://')
					? ''
					: 'border-error'}"
				bind:value={baseApiAddr}
			/>
			{#if !(baseApiAddr.startsWith('http://') || baseApiAddr.startsWith('https://'))}
				<span class="text-error">API地址必须以http://或https://开始</span>
			{/if}

			{#if providerType == RAG_PROVIDER_TYPE.RAG_PROVIDER_YD_QANYTHING}
				<legend class="fieldset-legend">AGENT ID </legend>
				<input type="text" class="input w-full" bind:value={agentId} placeholder="请输入QAnything Agent Id" />
			{/if}
			<legend class="fieldset-legend">API密钥 </legend>
			<input type="password" class="input w-full" bind:value={apiKey} placeholder="请输入API密钥" />
		</fieldset>
		<div class="modal-action">
			<button class="btn" onclick={() => props.onCancel()}>取消</button>
			<button
				class="btn btn-primary"
				disabled={!valid()}
				onclick={() => {
					if (props.config == undefined) {
						addConfig();
					} else {
						updateConfig();
					}
				}}>{props.config == undefined ? '增加' : '修改'}</button
			>
		</div>
	</div>
	<div class="modal-backdrop">
		<button onclick={() => props.onCancel()}>close</button>
	</div>
</dialog>
